﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SilverSock;

using Nuzzle.Protocol;

namespace Nuzzle.Network
{
    public class BaseClient
    {
        private SilverSocket _socket { get; set; }

        public BaseClient(SilverSocket socket)
        {
            this._socket = socket;
            this._socket.OnDataArrivalEvent += new SilverEvents.DataArrival(OnData);
            this._socket.OnSocketClosedEvent += new SilverEvents.SocketClosed(OnClose);
        }

        public void DisconnectLater(int time)
        {
            var delayer = new Utilities.Delayer<BaseClient>(GetType().GetMethod("Disconnect"), null, this, time);
            delayer.Start();
        }

        public void Disconnect()
        {
            try
            {
                this._socket.CloseSocket();
            }
            catch (Exception e)
            {
                Utilities.Logger.Error("Can't disconnect player : " + e.ToString());
            }
        }

        public virtual void OnClose() { }

        private void OnData(byte[] data)
        {
            try
            {
                BigEndianReader buffer = new BigEndianReader(data);

            reparse: ;

                var packet = new NetworkMessageReader(buffer);
                this.OnPacket(packet);
                if (packet.Reader.BytesAvailable > 0)
                    goto reparse;
            }
            catch { }
        }

        public virtual void OnPacket(NetworkMessageReader message) { }

        public virtual void Send(NetworkMessage message)
        {
            try
            {
                var packet = new Protocol.Formatter((int)message.ProtocolID);
                packet.Pack(message.WriterBuffer.Data);
                this._socket.Send(packet.get_Data);
                message.Dispose();   
            }
            catch { }
        }
    }
}
